import React from 'react'
import { MenuOutlined } from '@ant-design/icons'
import { useSortable } from '@dnd-kit/sortable'
import { CSS } from '@dnd-kit/utilities'

// 数组按数量分组
export const chunkArr = (arr, size) => {
    //判断如果不是数组(就没有length)，或者size没有传值，size小于1，就返回空数组
    if (!arr.length || !size || size < 1) return []
    let [start, end, result] = [null, null, []]
    for (let i = 0; i < Math.ceil(arr.length / size); i++) {
        start = i * size
        end = start + size
        result.push(arr.slice(start, end))
    }
    return result
}

// 根据指定长度分割对象
export const ObjectToArray = (obj, len) => {
    const keys = Object.keys(obj)
    const result = []
    for (let i = 0; i < keys.length; i += len) {
        const groupKeys = keys.slice(i, i + len)
        const newObj = {}
        for (const key of groupKeys) {
            newObj[key] = obj[key]
        }
        result.push(newObj)
    }
    return result
}

// 补零函数
export const fillZero = num => {
    if (num < 10) return '0' + num
    else return num
}

// rgb转16进制
export const colorHex = rgb => {
    let reg = /^(rgb|RGB)/
    let color = rgb
    if (reg.test(color)) {
        let strHex = '#'
        let colorArr = color.replace(/(?:\(|\)|rgb|RGB)*/g, '').split(',')
        for (let i = 0; i < colorArr.length; i++) {
            let hex = Number(colorArr[i]).toString(16)
            if (hex === '0') hex += hex
            strHex += hex
        }
        return strHex
    } else {
        return String(color)
    }
}

// 16进制颜色转换rgb
export const colorRgb = (hex, type) => {
    let reg = /^#([0-9a-fA-f]{3}|[0-9a-fA-f]{6})$/
    let color = hex?.toLowerCase()
    if (reg.test(color)) {
        if (color.length === 4) {
            let colorNew = '#'
            for (let i = 1; i < 4; i += 1) {
                colorNew += color.slice(i, i + 1).concat(color.slice(i, i + 1))
            }
            color = colorNew
        }
        let colorChange = []
        for (let i = 1; i < 7; i += 2) {
            colorChange.push(parseInt('0x' + color.slice(i, i + 2)))
        }
        return type === 1 ? colorChange.join(',') : 'rgb(' + colorChange.join(',') + ')'
    } else {
        return color
    }
}

// color 文字计算
export const colorCount = hex => {
    let color = hex.toLowerCase()
    let colorChange = []
    for (let i = 1; i < 7; i += 2) {
        colorChange.push(parseInt('0x' + color.slice(i, i + 2)))
    }
    const [r, g, b] = colorChange
    return ((r * 0.2126 + g * 0.7152 + b * 0.0722) / 255 - 0.5) * -999999
}

// 数字转金额
export const toMoney = (num, sma) => {
    num = num.toFixed(sma)
    num = parseFloat(num)
    num = num.toLocaleString()
    return num
}

// 广度遍历
export const breadthSearch = (tree, text, url) => {
    var stark = []
    stark = stark.concat(tree)
    while (stark.length) {
        var temp = stark.shift()
        if (temp.children) stark = stark.concat(temp.children)
        if (temp[text] === url) return temp
    }
}

// 根据对象value获取key
export const ValueSetKey = (Object, value) => {
    for (const key in Object) {
        if (Object.hasOwnProperty(key) && Object[key] === value) {
            return key
        }
    }
}

// 树形数据获取value (父级数据)
export const findParentNode = (treeData, value, key = 'uuid') => {
    for (let item of treeData) {
        if (item.children && item.children.length > 0) {
            if (item.children.some(obj => obj[key] === value)) {
                return item
            } else findParentNode(item.children, value, key)
        }
    }
    return null
}

// 拖动Table的设置
export const TableRow = ({ children, ...props }) => {
    const { attributes, listeners, setNodeRef, setActivatorNodeRef, transform, transition, isDragging } = useSortable({
        id: props['data-row-key'],
    })
    const style = {
        ...props.style,
        transform: CSS.Transform.toString(transform && { ...transform, scaleY: 1 })?.replace(
            /translate3d\(([^,]+),/,
            'translate3d(0,',
        ),
        transition,
        ...(isDragging ? { position: 'relative', zIndex: 9999 } : {}),
    }
    return (
        <tr {...props} ref={setNodeRef} style={style} {...attributes}>
            {React.Children.map(children, child => {
                if (child.key === 'uuid') {
                    return React.cloneElement(child, {
                        children: (
                            <MenuOutlined
                                ref={setActivatorNodeRef}
                                style={{ touchAction: 'none', cursor: 'move' }}
                                {...listeners}
                            />
                        ),
                    })
                }
                return child
            })}
        </tr>
    )
}

// 树转平
export const TreeToLevel = item => {
    let res = []
    item.forEach(key => {
        res.push(key)
        key.children && res.push(...TreeToLevel(key.children))
    })
    return res
}

// 过滤树形菜单可选
export const TreeFilterData = data => {
    let newData = data.map(v => {
        v.disabled = v.lowLevel === 0 ? false : true
        return v
    })
    newData.forEach(x => {
        x.children && (x.children = TreeFilterData(x.children))
    })
    return newData
}

// 过滤菜单
export const filterData = data => {
    var newData = data.filter(v => v.isEnabled !== 0)
    newData.forEach(x => x.children && (x.children = filterData(x.children)))
    return newData
}

// 排序字段
export const sortField = order => {
    let data = []
    order.forEach(item => {
        data = [
            ...data,
            {
                dataIndex: item.name,
                title: `${item.label}排序`,
                valueType: 'select',
                valueEnum: { asc: '正序', desc: '倒序' },
                hideInAdded: true,
                hideInModify: true,
                hideInTable: true,
            },
        ]
    })
    return data
}

// 过滤对象空value
export const filteredObj = obj => {
    let NewObj = Object.entries(obj).reduce((acc, [key, value]) => {
        if (value) acc[key] = value
        return acc
    }, {})
    return NewObj
}

// 树形数据获取value
export const findValue = (tree, key, value) => {
    for (let i = 0; i < tree.length; i++) {
        if (tree[i][key] === value) {
            return tree[i]
        } else if (tree[i].children && tree[i].children.length) {
            const result = findValue(tree[i].children, key, value)
            if (result) return result
        }
    }
    return null
}

// 半分数组
export const splitArray = arr => {
    const middle = Math.ceil(arr.length / 2)
    const firstHalf = arr.splice(0, middle)
    const secondHalf = arr
    return [firstHalf, secondHalf]
}

// 对比数据
export const hasCommonElement = (arr1, arr2) => {
    for (let i = 0; i < arr1.length; i++) {
        for (let j = 0; j < arr2.length; j++) {
            if (arr1[i] === arr2[j]) {
                return true
            }
        }
    }
    return false
}

// 解url参数
export const parseURLParams = url => {
    const urlParams = new URLSearchParams(url)
    const params = {}
    for (const [key, value] of urlParams.entries()) {
        params[key] = value
    }
    return params
}

// 字符串指定位置添加新字符
export const insertCharacter = (originalString, insertChar, position) => {
    return originalString.slice(0, position) + insertChar + originalString.slice(position)
}

// 递归遍历树形数据并获取指定字段的值
export const getValuesFromTree = (tree, fieldName) => {
    const values = []

    const traverse = node => {
        console.log('node', node)
        if (node[fieldName]) {
            values.push(node[fieldName])
        }
        if (node.children) {
            node.children.forEach(child => {
                traverse(child)
            })
        }
    }

    traverse(tree)

    return values
}

// 指定长度分割字符串
export const segmentationString = (string, number) => {
    const regex = new RegExp(`.{1,${number}}`, 'g')
    return string.match(regex)
}

export const insertNewlineEveryFourChars = str => {
    return str.replace(/(.{4})/g, '$1\n')
}

// 取两值之间的随机数
export const getRandomNumber = (min, max) => {
    return Math.floor(Math.random() * (max - min + 1)) + min
}
